#coding=utf-8

import sys
import time
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

sysType = sys.getfilesystemencoding()
browser = webdriver.Chrome()

def convertStrTo_(url):
    pattern = r'^/api'
    replaceResult = re.sub(pattern, '', url)
    splitArr = replaceResult.split('/')
    i = 0
    for item in splitArr:
        if item == '':
            splitArr.pop(i)
        i = i + 1
    return '_'.join(splitArr)

try:
    browser.get('http://rap2.local:32600/account/login')
    time.sleep(30)
    browser.get('http://rap2.local:32600/repository/editor?id=120&mod=795&itf=8085')

    wait = WebDriverWait(browser, 10)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.InterfaceList')))

    interfaceEle = browser.find_element(By.CSS_SELECTOR, '.InterfaceList')
    interfaceArr = []
    interfaceWrappers = interfaceEle.find_elements(By.CSS_SELECTOR, '.sortable .Interface')
    for item in interfaceWrappers:
        try:
            aEl = item.find_element(By.CSS_SELECTOR, 'span a')
            aHref = aEl.get_attribute('href')
            name = item.find_element(By.CSS_SELECTOR, 'a .name').text
            url = item.find_element(By.CSS_SELECTOR, '.url').text
            interfaceArr.append({'name': name, 'url': url, 'aHref': aHref})

        except Exception:
            print(Exception)

    print(interfaceArr)
    for itm in interfaceArr:
            print('// ' + itm['name'])
            print('// ' + itm['url'])
            interfaceFnName = convertStrTo_(itm['url'])
            interFaceFnContent = """export function {0}(
                    data,
                    reqExtCfg,
                    successCb
                ) {2}
                return requestWrapper(
                    {{
                        url: '{1}',
                        method: 'post',
                        data
                    }},
                    reqExtCfg,
                    successCb
                ){3}
            """.format(interfaceFnName, itm['url'], '{', '}')
            print(interFaceFnContent)

    print('')
    # 集中打印所有的接口
    for itm in interfaceArr:
        print(itm['url'])

finally:
    print('finally')
#     browser.close()
